import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Transfer,
  message,
  Row,
  Col,
  Tabs,
  Statistic,
  Progress,
  Avatar,
  List,
  Tooltip,
  Dropdown,
  Menu,
  Badge,
  Typography,
  Alert,
  Descriptions,
  Divider,
  DatePicker,
  Switch,
  Checkbox,
  Drawer,
  Popconfirm,
  Empty,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  TeamOutlined,
  BookOutlined,
  SettingOutlined,
  SearchOutlined,
  ExportOutlined,
  ImportOutlined,
  EyeOutlined,
  StarOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  MoreOutlined,
  CopyOutlined,
  UserAddOutlined,
  FileTextOutlined,
  MessageOutlined,
  CalendarOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import styled from "styled-components";
import { getFullCourseData, getStatistics } from "../../../utils/mockData";

const { Option } = Select;
const { TabPane } = Tabs;
const { Text, Title } = Typography;
const { RangePicker } = DatePicker;

// 样式组件
const ManagementContainer = styled.div`
  padding: 24px;
`;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const CourseCard = styled(Card)`
  margin-bottom: 16px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
`;

// 接口定义
interface Course {
  id: string;
  name: string;
  code: string;
  semester: string;
  credits: number;
  description: string;
  status: "active" | "inactive" | "ended";
  maxStudents: number;
  currentStudents: number;
  teacher: Teacher;
  classes: Class[];
  schedule: string;
  location: string;
  createTime: string;
}

interface Teacher {
  id: string;
  name: string;
  email: string;
  department: string;
  title: string;
  avatar?: string;
  phone: string;
}

interface Class {
  id: string;
  name: string;
  code: string;
  grade: string;
  major: string;
  studentCount: number;
  maxStudents: number;
  students: Student[];
}

interface Student {
  id: string;
  name: string;
  studentNumber: string;
  grade: string;
  major: string;
  email: string;
  avatar?: string;
  phone: string;
  status: "active" | "suspended" | "graduated";
  enrollTime: string;
  gpa?: number;
}

const ClassManagement: React.FC = () => {
  const [courses, setCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedCourse, setSelectedCourse] = useState<Course | null>(null);
  const [activeTab, setActiveTab] = useState("courses");

  // 模态框状态
  const [courseDetailVisible, setCourseDetailVisible] = useState(false);
  const [addStudentModalVisible, setAddStudentModalVisible] = useState(false);
  const [editClassModalVisible, setEditClassModalVisible] = useState(false);
  const [selectedClass, setSelectedClass] = useState<Class | null>(null);

  // 表单
  const [courseForm] = Form.useForm();
  const [studentForm] = Form.useForm();
  const [classForm] = Form.useForm();

    // 使用统一的数据源
  const generateMockData = () => {
    return getFullCourseData();
  };

  // 初始化数据
  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      setLoading(true);
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      const mockData = generateMockData();
      setCourses(mockData);
    } catch (error) {
      message.error("加载数据失败");
    } finally {
      setLoading(false);
    }
  };

  // 查看课程详情
  const handleViewCourseDetail = (course: Course) => {
    setSelectedCourse(course);
    setCourseDetailVisible(true);
  };

  // 添加学生到班级
  const handleAddStudent = (classData: Class) => {
    setSelectedClass(classData);
    setAddStudentModalVisible(true);
  };

  // 编辑班级信息
  const handleEditClass = (classData: Class) => {
    setSelectedClass(classData);
    classForm.setFieldsValue({
      name: classData.name,
      code: classData.code,
      maxStudents: classData.maxStudents,
      major: classData.major,
      grade: classData.grade
    });
    setEditClassModalVisible(true);
  };

  // 删除学生
  const handleDeleteStudent = (studentId: string, classId: string) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这名学生吗？",
      onOk: () => {
        // 模拟删除操作
        setCourses(prev => prev.map(course => ({
          ...course,
          classes: course.classes.map(cls => {
            if (cls.id === classId) {
              return {
                ...cls,
                students: cls.students.filter(s => s.id !== studentId),
                studentCount: cls.studentCount - 1
              };
            }
            return cls;
          })
        })));
        message.success("学生删除成功");
      }
    });
  };

  // 课程表格列定义
  const courseColumns: ColumnsType<Course> = [
    {
      title: "课程信息",
      key: "courseInfo",
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', fontSize: '16px' }}>
            {record.name}
          </div>
          <div style={{ color: '#666', fontSize: '14px' }}>
            {record.code} | {record.semester} | {record.credits}学分
        </div>
          <div style={{ color: '#999', fontSize: '12px' }}>
            {record.schedule} | {record.location}
          </div>
        </div>
      )
    },
    {
      title: "授课教师",
      key: "teacher",
      render: (_, record) => (
        <Space>
          <Avatar src={record.teacher.avatar} size="small" />
          <div>
            <div>{record.teacher.name}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>
              {record.teacher.title}
            </div>
          </div>
        </Space>
      )
    },
    {
      title: "班级情况",
      key: "classes",
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>
            {record.classes.length}个班级
          </div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            共{record.currentStudents}名学生
          </div>
        </div>
      )
    },
    {
      title: "选课情况",
      key: "enrollment",
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>
            {record.currentStudents}/{record.maxStudents}
          </div>
          <Progress
            percent={Math.round((record.currentStudents / record.maxStudents) * 100)} 
            size="small"
            status={record.currentStudents >= record.maxStudents ? "exception" : "active"}
          />
        </div>
      )
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Tag color={status === "active" ? "green" : status === "inactive" ? "orange" : "red"}>
          {status === "active" ? "进行中" : status === "inactive" ? "未开始" : "已结束"}
        </Tag>
      )
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
            <Button
              type="link"
              icon={<EyeOutlined />}
            onClick={() => handleViewCourseDetail(record)}
          >
            查看详情
          </Button>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="edit" icon={<EditOutlined />}>
                  编辑课程
                </Menu.Item>
                <Menu.Item key="delete" icon={<DeleteOutlined />} danger>
                  删除课程
                </Menu.Item>
              </Menu>
            }
          >
            <Button type="link" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      )
    }
  ];

  // 学生表格列定义
  const studentColumns: ColumnsType<Student> = [
    {
      title: "学生信息",
      key: "studentInfo",
      render: (_, record) => (
        <Space>
          <Avatar src={record.avatar} />
          <div>
            <div style={{ fontWeight: 'bold' }}>{record.name}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>
              {record.studentNumber}
            </div>
          </div>
        </Space>
      )
    },
    {
      title: "专业年级",
      key: "majorGrade",
      render: (_, record) => (
        <div>
          <div>{record.major}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {record.grade}
          </div>
        </div>
      )
    },
    {
      title: "联系方式",
      key: "contact",
      render: (_, record) => (
        <div>
          <div>{record.email}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {record.phone}
          </div>
        </div>
      )
    },
    {
      title: "GPA",
      dataIndex: "gpa",
      key: "gpa",
      render: (gpa: number) => (
        <Tag color={gpa >= 3.5 ? "green" : gpa >= 3.0 ? "blue" : "orange"}>
          {gpa}
        </Tag>
      )
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Badge 
          status={status === "active" ? "success" : status === "suspended" ? "warning" : "default"} 
          text={status === "active" ? "在读" : status === "suspended" ? "休学" : "毕业"}
        />
      )
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          <Button type="link" size="small">查看详情</Button>
          <Popconfirm
            title="确定要删除这名学生吗？"
            onConfirm={() => handleDeleteStudent(record.id, selectedClass?.id || "")}
          >
            <Button type="link" size="small" danger>移除</Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <ManagementContainer>
      <StyledCard
        title="班级管理 - 课程中心模式"
        extra={
          <Space>
            <Button icon={<ImportOutlined />}>
              批量导入
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => window.location.href = "/teacher/courses/add"}
            >
              新建课程
            </Button>
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="课程管理" key="courses">
            <Table
              columns={courseColumns}
              dataSource={courses}
              rowKey="id"
              loading={loading}
              pagination={{
                total: courses.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 门课程`,
              }}
            />
          </TabPane>

          <TabPane tab="数据统计" key="statistics">
            <Row gutter={16}>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="总课程数"
                    value={getStatistics().totalCourses}
                    prefix={<BookOutlined />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="总学生数"
                    value={getStatistics().totalStudents}
                    prefix={<TeamOutlined />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="总班级数"
                    value={getStatistics().totalClasses}
                    prefix={<UserOutlined />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="进行中课程"
                    value={getStatistics().activeCourses}
                    prefix={<ClockCircleOutlined />}
                  />
                </Card>
              </Col>
            </Row>
          </TabPane>
        </Tabs>
      </StyledCard>

      {/* 课程详情抽屉 */}
      <Drawer
        title={`课程详情 - ${selectedCourse?.name}`}
        placement="right"
        width={800}
        open={courseDetailVisible}
        onClose={() => setCourseDetailVisible(false)}
        extra={
          <Space>
            <Button icon={<EditOutlined />}>编辑课程</Button>
            <Button icon={<FileTextOutlined />}>导出数据</Button>
          </Space>
        }
      >
        {selectedCourse && (
                      <div>
            {/* 课程基本信息 */}
            <Card title="课程基本信息" style={{ marginBottom: 16 }}>
              <Descriptions column={2} bordered>
                <Descriptions.Item label="课程名称">{selectedCourse.name}</Descriptions.Item>
                <Descriptions.Item label="课程代码">{selectedCourse.code}</Descriptions.Item>
                <Descriptions.Item label="开课学期">{selectedCourse.semester}</Descriptions.Item>
                <Descriptions.Item label="课程学分">{selectedCourse.credits}学分</Descriptions.Item>
                <Descriptions.Item label="上课时间">{selectedCourse.schedule}</Descriptions.Item>
                <Descriptions.Item label="上课地点">{selectedCourse.location}</Descriptions.Item>
                <Descriptions.Item label="授课教师">{selectedCourse.teacher.name}</Descriptions.Item>
                <Descriptions.Item label="教师职称">{selectedCourse.teacher.title}</Descriptions.Item>
                <Descriptions.Item label="课程描述" span={2}>
                  {selectedCourse.description}
                </Descriptions.Item>
              </Descriptions>
            </Card>

            {/* 班级管理 */}
            <Card 
              title="班级管理" 
              extra={
                <Button type="primary" icon={<PlusOutlined />}>
                  添加班级
                </Button>
              }
            >
              <List
                dataSource={selectedCourse.classes}
                renderItem={(classItem) => (
                  <List.Item
                    actions={[
                      <Button 
                        type="link" 
                        icon={<EyeOutlined />}
                        onClick={() => {
                          setSelectedClass(classItem);
                          setAddStudentModalVisible(true);
                        }}
                      >
                        查看学生
                      </Button>,
                      <Button 
                        type="link" 
                        icon={<EditOutlined />}
                        onClick={() => handleEditClass(classItem)}
                      >
                        编辑
                      </Button>,
                      <Button 
                        type="link" 
                        icon={<UserAddOutlined />}
                        onClick={() => handleAddStudent(classItem)}
                      >
                        添加学生
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<Avatar icon={<TeamOutlined />} />}
                      title={
                        <Space>
                          <span>{classItem.name}</span>
                          <Tag color="blue">{classItem.code}</Tag>
                        </Space>
                      }
                      description={
                        <div>
                          <div>{classItem.grade} {classItem.major}</div>
                          <div style={{ marginTop: 4 }}>
                            <Text type="secondary">
                              学生数: {classItem.studentCount}/{classItem.maxStudents}
                            </Text>
                            <Progress 
                              percent={Math.round((classItem.studentCount / classItem.maxStudents) * 100)} 
                              size="small" 
                              style={{ marginLeft: 8, width: 100 }}
                            />
                  </div>
                  </div>
                      }
                    />
                  </List.Item>
                )}
                  />
                </Card>
                    </div>
        )}
      </Drawer>

      {/* 学生管理模态框 */}
      <Modal
        title={`学生管理 - ${selectedClass?.name}`}
        open={addStudentModalVisible}
        onCancel={() => setAddStudentModalVisible(false)}
        width={1200}
        footer={null}
      >
        {selectedClass && (
                    <div>
                    <div style={{ marginBottom: 16 }}>
              <Space>
                <Button type="primary" icon={<UserAddOutlined />}>
                  添加学生
                </Button>
                <Button icon={<ImportOutlined />}>
                  批量导入
                </Button>
                <Button icon={<ExportOutlined />}>
                  导出名单
                </Button>
                <Button icon={<MessageOutlined />}>
                  发送通知
                </Button>
              </Space>
                    </div>
            
                  <Table
              columns={studentColumns}
              dataSource={selectedClass.students}
                    rowKey="id"
              pagination={{
                total: selectedClass.students.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 名学生`,
              }}
            />
                            </div>
        )}
      </Modal>

      {/* 编辑班级模态框 */}
      <Modal
        title="编辑班级信息"
        open={editClassModalVisible}
        onCancel={() => setEditClassModalVisible(false)}
        onOk={() => {
          classForm.validateFields().then(values => {
            // 模拟更新操作
            setCourses(prev => prev.map(course => ({
              ...course,
              classes: course.classes.map(cls => {
                if (cls.id === selectedClass?.id) {
                  return {
                    ...cls,
                    ...values
                  };
                }
                return cls;
              })
            })));
            message.success("班级信息更新成功");
            setEditClassModalVisible(false);
                        });
                      }}
                    >
        <Form form={classForm} layout="vertical">
              <Form.Item
                name="name"
            label="班级名称"
            rules={[{ required: true, message: "请输入班级名称" }]}
              >
            <Input placeholder="请输入班级名称" />
              </Form.Item>
              <Form.Item
                name="code"
            label="班级代码"
            rules={[{ required: true, message: "请输入班级代码" }]}
              >
            <Input placeholder="请输入班级代码" />
              </Form.Item>
              <Form.Item
            name="maxStudents"
            label="最大学生数"
            rules={[{ required: true, message: "请输入最大学生数" }]}
              >
            <InputNumber min={1} max={100} style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item
            name="major"
            label="专业"
            rules={[{ required: true, message: "请选择专业" }]}
              >
            <Select placeholder="请选择专业">
              <Option value="计算机科学与技术">计算机科学与技术</Option>
              <Option value="软件工程">软件工程</Option>
              <Option value="数据科学与大数据技术">数据科学与大数据技术</Option>
              <Option value="人工智能">人工智能</Option>
                </Select>
              </Form.Item>
              <Form.Item
            name="grade"
            label="年级"
            rules={[{ required: true, message: "请选择年级" }]}
              >
            <Select placeholder="请选择年级">
              <Option value="2020级">2020级</Option>
              <Option value="2021级">2021级</Option>
              <Option value="2022级">2022级</Option>
              <Option value="2023级">2023级</Option>
              <Option value="2024级">2024级</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </ManagementContainer>
  );
};

export default ClassManagement;
